package com.cloud.template.netty.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;


/**
 * netty服务（使用FixedLengthFrameDecoder解决tcp的粘包和拆包）
 * FixedLengthFrameDecoder是以设置固定长度的解码器，
 * 按照固定长度解码，如果是半包消息，会等待下一个包进行拼包，直到读取到一个完整的包
 * Created by Viole on 2018/1/2.
 */
public class FixedTcpNettyServer {

    private int port;
    public FixedTcpNettyServer(int port) {
        this.port = port;
    }
    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        System.out.println("准备运行端口：" + port);
        try {
            ServerBootstrap b = new ServerBootstrap();
            b = b.group(bossGroup, workerGroup);
            b = b.channel(NioServerSocketChannel.class);
            b = b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast(new ServerHandler());//服务端处理
                }
            });
            b = b.option(ChannelOption.SO_BACKLOG, 128);
            b = b.childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            /***
             * 优雅关闭
             */
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8000;
        }
        try {
            new FixedTcpNettyServer(port).run();
        }catch (Exception e){
            e.printStackTrace();
        }
        //通过cmd窗口的telnet 127.0.0.1 8000运行
    }
}
